import { create } from 'zustand'

// 轻量内置类型与内存版 API，避免未引入真实 API 时的运行时错误
export type CampaignStatus = 'draft' | 'scheduled' | 'running' | 'completed'

export interface MailCampaignRecord {
  id: string
  title: string
  segment: string
  scheduledAt: string
  status: CampaignStatus
  createdBy?: string
  deliverRate?: number
  sentCount?: number
  feedback?: string
}

export type MailCampaign = MailCampaignRecord

const __memoryCampaigns: MailCampaign[] = []

const mailCampaignAPI = {
  create: async (payload: Partial<MailCampaign>): Promise<{ data: MailCampaign }> => {
    const rec: MailCampaign = {
      id: Math.random().toString(36).slice(2),
      title: payload.title || '未命名任务',
      segment: payload.segment || '全部用户',
      scheduledAt: payload.scheduledAt || new Date().toISOString(),
      status: (payload.status as CampaignStatus) || 'scheduled',
      createdBy: payload.createdBy || 'system',
      deliverRate: payload.deliverRate || 0,
      sentCount: payload.sentCount || 0,
      feedback: payload.feedback,
    }
    __memoryCampaigns.unshift(rec)
    return Promise.resolve({ data: rec })
  },
  list: async (): Promise<{ data: MailCampaign[] }> => {
    return Promise.resolve({ data: [...__memoryCampaigns].slice(0, 20) })
  },
  update: async (id: string, patch: Partial<MailCampaign>): Promise<{ data: MailCampaign }> => {
    const idx = __memoryCampaigns.findIndex((c) => c.id === id)
    if (idx >= 0) {
      __memoryCampaigns[idx] = { ...__memoryCampaigns[idx], ...patch }
      return Promise.resolve({ data: __memoryCampaigns[idx] })
    }
    throw new Error('campaign not found')
  },
}

interface MailCenterState {
  campaigns: MailCampaign[]
  loading: boolean
  lastSyncedAt?: string
  scheduleCampaign: (payload: {
    title: string
    segment: string
    scheduledAt?: string
    status?: CampaignStatus
    createdBy?: string
    feedback?: string
  }) => Promise<void>
  fetchCampaigns: () => Promise<void>
  updateCampaignStatus: (id: string, status: CampaignStatus, deliverRate?: number, sentCount?: number, feedback?: string) => Promise<void>
}

export const useMailCenterStore = create<MailCenterState>((set, get) => ({
  campaigns: [],
  loading: false,
  scheduleCampaign: async (payload) => {
    const response = await mailCampaignAPI.create(payload)
    const record = response.data
    set((state) => ({
      campaigns: [record, ...state.campaigns].slice(0, 20),
      lastSyncedAt: new Date().toISOString(),
    }))
  },
  fetchCampaigns: async () => {
    if (get().loading) return
    set({ loading: true })
    try {
      const response = await mailCampaignAPI.list()
      set({
        campaigns: response.data,
        loading: false,
        lastSyncedAt: new Date().toISOString(),
      })
    } catch (error) {
      console.error('fetchCampaigns failed', error)
      set({ loading: false })
    }
  },
  updateCampaignStatus: async (id, status, deliverRate, sentCount, feedback) => {
    try {
      const response = await mailCampaignAPI.update(id, { status, deliverRate, sentCount, feedback })
      const updated = response.data
      set((state) => ({
        campaigns: state.campaigns.map((item) => (item.id === id ? updated : item)),
        lastSyncedAt: new Date().toISOString(),
      }))
    } catch (error) {
      console.error('updateCampaignStatus failed', error)
    }
  },
}))

